package com.sscaipiao.android.activity;

import java.io.IOException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.sscaipiao.android.R;
import com.sscaipiao.android.common.Constants;
import com.sscaipiao.android.model.User;
import com.sscaipiao.android.utils.StringUtil;
import com.sscaipiao.android.utils.UserDataServiceHelper;

public class RegistActivity extends Activity implements OnClickListener{
	
	private Button backButton;
	private Button validateCodeButton;
	private Button finishButton;
	private TextView protocol;
	
	private EditText  regist_txt_phone;
	private EditText  regist_txt_password;
	private EditText  regist_txt_repeat_password;
	private EditText  regist_txt_validate_code;
	
	private CheckBox regist_checkbox_read_and_confirm;
	private String validateCode;
	
	private User user;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
		.detectDiskReads().detectDiskWrites().detectNetwork()
		.penaltyLog().build());
		StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
		.detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
		.penaltyLog().penaltyDeath().build());

		super.onCreate(savedInstanceState);
		setContentView(R.layout.regist1);
		
		Intent i = this.getIntent();
		if (!i.equals(null)) {
			Bundle b = i.getExtras();
			if (b != null) {
				if (b.containsKey(Constants.USER)) {
					user = (User) b.get(Constants.USER);
				}
			}
		}
		
		backButton =  (Button) findViewById(R.id.regist_button_back);
		validateCodeButton = (Button) findViewById(R.id.regist1_button_validate_code);
		finishButton = (Button) findViewById(R.id.regist_button_finish);
		protocol = (TextView) findViewById(R.id.regist_txt_protocol);
		
		backButton.setOnClickListener(this);
		validateCodeButton.setOnClickListener(this);
		finishButton.setOnClickListener(this);
		protocol.setOnClickListener(this);
		
		regist_txt_phone = (EditText)  findViewById(R.id.regist_txt_phone);
		regist_txt_password = (EditText)  findViewById(R.id.regist_txt_password);
		regist_txt_repeat_password = (EditText)  findViewById(R.id.regist_txt_repeat_password);
		regist_txt_validate_code = (EditText)  findViewById(R.id.regist_txt_validate_code);
		
		regist_checkbox_read_and_confirm =  (CheckBox)  findViewById(R.id.regist_checkbox_read_and_confirm);
	}


	@Override
	public void onClick(View v) {
		if(R.id.regist_button_back == v.getId()) {

//			Intent intent = new Intent(RegistActivity.this, LoginActivity.class);
//			Bundle b = new Bundle();
//			intent.putExtras(b);
//			startActivity(intent);
			RegistActivity.this.finish();  
			
		}else if ( R.id.regist_txt_protocol == v.getId()) {
			new AlertDialog.Builder(this).setTitle("用户投注协议")  
			                .setMessage(getResources().getString(R.string.user_protocol))  
			                .setPositiveButton("确定", null)  
			                .show();  
			
		} else if (R.id.regist1_button_validate_code == v.getId()) {
			EditText phone =  (EditText) findViewById(R.id.regist_txt_phone);
			if (StringUtil.isNotEmptyString(phone.getText().toString())){
				Toast.makeText(RegistActivity.this, "验证码已发送，请查收",
						Toast.LENGTH_SHORT).show();
				
				 String retStr = UserDataServiceHelper.getValidateCode(RegistActivity.this,
						 phone.getText().toString(),user);
				 String[] result  = retStr.split(Constants.STRING_SPLITE);
				 if(result.length > 0) {
					 if(Constants.LOGIN_SUCCESS_CODE.equals(result[0])) {
						 validateCode = result[2];
					 } else {
							new AlertDialog.Builder(this).setTitle("错误")  
			                .setMessage(result[1])  
			                .setPositiveButton("确定", null)  
			                .show(); 
					 }
				 } else {
						new AlertDialog.Builder(this).setTitle("错误")  
		                .setMessage("请检查网络连接情况")  
		                .setPositiveButton("确定", null)  
		                .show();  
				 }
			} else {
				new AlertDialog.Builder(this).setTitle("错误")  
                .setMessage("请先填写手机号码")  
                .setPositiveButton("确定", null)  
                .show();  
			}
			
		} else if (R.id.regist_button_finish == v.getId()) {
			
			String errorMsg = "";
			
			if(regist_txt_phone.getText() == null || StringUtil.isEmptyString(regist_txt_phone.getText().toString())){
				errorMsg += "手机号不能为空\n";
				
			}
			if(regist_txt_password.getText() == null || regist_txt_repeat_password.getText() == null || StringUtil.isEmptyString(regist_txt_password.getText().toString()) || 
					StringUtil.isEmptyString(regist_txt_repeat_password.getText().toString())){
				errorMsg += "密码不能为空\n";
				
			} else if( !regist_txt_password.getText().toString().equals(regist_txt_repeat_password.getText().toString()) ){
				errorMsg += "2次输入密码不匹配\n";
				
			}
			if( regist_txt_validate_code.getText() == null || StringUtil.isEmptyString(regist_txt_validate_code.getText().toString())){
				errorMsg += "验证码不能为空\n";
				
			} else if (StringUtil.isEmptyString(validateCode)){
				errorMsg += "请点击获取验证码\n";
			} else if ( !validateCode.equals(regist_txt_validate_code.getText().toString())){
				errorMsg += "验证码不匹配\n";
			}
			 if (regist_checkbox_read_and_confirm == null || ! regist_checkbox_read_and_confirm.isChecked()) {
				 errorMsg += "请阅读并勾选确认  《电话采购协议》\n";
			 }
			 
			 if( StringUtil.isNotEmptyString(errorMsg)) {
					new AlertDialog.Builder(this).setTitle("输入数据不完整")  
	                .setMessage(errorMsg)  
	                .setPositiveButton("确定", null)  
	                .show(); 
			 } else {
				 User retUser = null;
				 try {
					 if(user == null){
						 user = new User();
						 user.setAccount(regist_txt_phone.getText().toString());
						 user.setPassword(regist_txt_password.getText().toString());
						 user.setRand(regist_txt_validate_code.getText().toString());
						 //user.setName(regist_txt_phone.getText().toString());
						 //user.setToken(regist_txt_validate_code.getText().toString());
					 }
					 retUser = UserDataServiceHelper.register(RegistActivity.this, user);
				} catch (IOException e) {
					new AlertDialog.Builder(this).setTitle("注册失败")  
	                .setMessage(e.getMessage())  
	                .setPositiveButton("确定", null)  
	                .show(); 
				}
				 
				 if(retUser != null ){
					 
					 if(retUser.getStatus().equals(Constants.LOGIN_SUCCESS_CODE)){
							Intent intent = new Intent(RegistActivity.this, Regist2Activity.class);
							Bundle b = new Bundle();
							if (user == null) {
								user = new User();
							}
							
							Log.v("regist_txt_phone", regist_txt_phone.getText().toString());
							user.setAccount(regist_txt_phone.getText().toString());
							user.setPassword(regist_txt_repeat_password.getText().toString());
							user.setRand(regist_txt_validate_code.getText().toString());
							user.setToken(retUser.getToken());
							b.putSerializable(Constants.USER, user);
							intent.putExtras(b);
							startActivity(intent);
					 } else {
							new AlertDialog.Builder(this).setTitle("注册失败")  
			                .setMessage(retUser.getMessage())  
			                .setPositiveButton("确定", null)  
			                .show(); 
					 }
				 }

			 }
		

		} else {
			return;
		}
	}
}
